﻿using AutoMapper;
using Common.Infrastructrue.Interface;
using Common.Service;
using MediatR;
using Microsoft.AspNetCore.Http;
using RabitPart.ReadApi.Application.RBACrelationship.RELUserShow;
using System.Security.Claims;

namespace RabitPart.ReadApi.Application.RBACrelationship.Relroleperm
{
    public class GetTreeRolePermCommanHandel : IRequestHandler<GetTreeRolePermComman, ApiResult<IList<GetTreeRolePermCommanResponstity>>>
    {
        private readonly IMapper mapper;
        private readonly IRel_user_roleResponstity useroleRE;//用户角色
        private readonly IRelrolepermResponsstity rolepermRE;//角色权限
        private readonly IUserResponstity userRE;//用户
        private readonly IRoleResponstity RoleRE;//角色
        private readonly ISys_permsResponstity permissionRE;//权限
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ILogger<GetTreeRolePermCommanHandel> logger;
        public GetTreeRolePermCommanHandel(IMapper mapper, IRel_user_roleResponstity useroleRE, IRelrolepermResponsstity rolepermRE, IUserResponstity userRE, IRoleResponstity RoleRE, ISys_permsResponstity permissionRE,ILogger<GetTreeRolePermCommanHandel> logger, IHttpContextAccessor _httpContextAccessor)
        {
            this.mapper = mapper;
            this.useroleRE = useroleRE;
            this.logger = logger;
            this.userRE = userRE;
            this.RoleRE = RoleRE;
            this.permissionRE = permissionRE;
            this.rolepermRE = rolepermRE; 
            this._httpContextAccessor = _httpContextAccessor;
        }
         
        public async Task<ApiResult<IList<GetTreeRolePermCommanResponstity>>> Handle(GetTreeRolePermComman request, CancellationToken cancellationToken)
        {
            var list = await GetTree(); 
            var user = _httpContextAccessor.HttpContext?.User.FindFirstValue("Sub");
            var userId = Convert.ToInt32(_httpContextAccessor.HttpContext?.User.FindFirstValue("Id")); 
            //获取用户拥有的权限
            var userrole = await userRE.GetAllAsync(x => x.uId == userId);
            var roleIds = userrole.Select(x=>x.rId).ToArray();
            var userperm = await rolepermRE.GetAllAsync(x => roleIds.Contains(x.rId));
            var permIds = userperm.Select(x=>x.pId).ToArray();
            //获取角色拥有的权限 
            list = list.Where(x=>permIds.Contains(x.pId)).ToList();
            return ApiResult<IList<GetTreeRolePermCommanResponstity>>.Success(list,StatusCodeEnum.Ok);

        }

        //递归获取角色权限树
        public async Task<IList<GetTreeRolePermCommanResponstity>> GetTree (int psuperior = 0)
        {
            var Tree = await permissionRE.GetAllAsync(x => x.psuperior == psuperior);
            var result = mapper.Map<IList<GetTreeRolePermCommanResponstity>>(Tree);
            foreach (var item in result)
            {
                item.Children = await GetTree(item.pId);
            }
            return result;
        }
        

    }
}
